
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.Clinic;
import org.springframework.samples.petclinic.Owner;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.WebDataBinder;

import org.groovyflow.spring.locator.*
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ajax.json.*;

/**
 * JavaBean Form controller that is used to search for <code>Owner</code>s by
 * last name.
 *
 * @author Juergen Hoeller
 * @author Ken Krebs
 */
@Controller
public class FindOwnersController {

	private final Clinic clinic;
	def beanLocator = new BeanLocatorImpl();

	/*@Autowired
	public FindOwnersController(Clinic clinic) {
		this.clinic = clinic;
	}*/
	
	def getClinic(){
		return beanLocator.getBean("clinic")
	}

    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
        //dataBinder.setDisallowedFields(new String[] {"id"});
    	String[] arr = {"id"}
        dataBinder.setDisallowedFields(arr);
    }

	@RequestMapping(method = [RequestMethod.GET])
	public  String setupForm(Model model) {
		model.addAttribute("owner", new Owner());
		println 'request header: ' + AjaxContext.getRequest().getHeader("X-Requested-With")
		println "xhr? " + AjaxContext.isXHR()
		if(AjaxContext.isXHR()){
		    println 'xhr'
			AjaxContext.json.addPartials("contentPartial", "findOwners", model.asMap());
			AjaxContext.json.writeJson();
			return null
		}
	    return "findOwners";
	}

	@RequestMapping(method = [RequestMethod.POST])
	public  String processSubmit(Owner owner, BindingResult result, Model model,
		HttpServletRequest request, HttpServletResponse response) {
		    println 'groovy FindOwnersController processSubmit'
		    System.out.println("!!!! " + AjaxContext.isXHR());
		    if(AjaxContext.isXHR()){
			    println "lastName " + owner.getLastName()
				
				AjaxContext.json.addPartials("jsPartial", "js", model.asMap());
				AjaxContext.json.map.put("javascriptBefore", """
				 \$('#lastName').fadeOut()
				""")
				AjaxContext.json.map.put("javascriptAfter", """
				 \$('#lastName').fadeIn('slow')
				""")
				
				AjaxContext.json.writeJson();
				
		        return null;
	        }
	
		// find owners by last name
		Collection<Owner> results = this.getClinic().findOwners(owner.getLastName());
		if (results.size() < 1) {
			// no owners found
			result.rejectValue("lastName", "notFound", "not found");
			return "findOwners";
		}
		if (results.size() > 1) {
			// multiple owners found
			model.addAttribute("selections", results);
			return "owners";
		}
		else {
			// 1 owner found
			owner = results.iterator().next();
			return "redirect:owner.do?ownerId=" + owner.getId();
		}
	}

}
